package com.xijing.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.xijing.model.*;

public class AdminDAO extends BaseDAO{
	
	private String columnFieldMapper4All = "SU_ID, SU_RealName, SU_LoginName, SU_Password,SU_State";


	/**
	 * 根据对象新增记录
	 * @param admin
	 * @return
	 */
	public int insertAdmin(SYS_User admin) {
		Connection conn = getConnection();
		QueryRunner qr = new QueryRunner();
		String sql = "insert into SYS_User ("+columnFieldMapper4All+")"
					+ " values"
					+ " (?, ?, ?,?,?)";
		try {
			int count = qr.update(conn, sql, 
					admin.getSU_ID(), 
					admin.getSU_RealName(), 
					admin.getSU_LoginName(),
					admin.getSU_Password(),
					admin.getSU_State());
			
			return count;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return 0;
	}

	/**
	 * 根据条件(通常是主键)来删除记录
	 * @param aid
	 * @return
	 */
	public int deleteAdmin(int aid) {
		Connection conn = getConnection();
		QueryRunner qr = new QueryRunner();
		String sql = "delete from SYS_User where SU_ID=?";
		try {
			int count = qr.update(conn, sql, aid);
			return count;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return 0;
	}

	/**
	 * 根据条件修改更新记录
	 * @param aid
	 * @param phoneNumber
	 * @return
	 */
	public int updateAdmin(int aid, String name) {
		Connection conn = getConnection();
		QueryRunner qr = new QueryRunner();
		String sql = "update SYS_User set SU_RealName = ? where SU_ID = ?";
		try {
			int count = qr.update(conn, sql, new Object[] { name, aid });
			return count;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return 0;
	}

	/**
	 * 查询获取一个对象
	 * @param aid
	 * @return
	 */
	public SYS_User getAdmin(String loginName,String pwd) {
		Connection conn = getConnection();
		QueryRunner qr = new QueryRunner();
		String sql = "SELECT " + columnFieldMapper4All + " FROM SYS_User where SU_LoginName=? and SU_Password=?";
		try {
			SYS_User admin = qr.query(conn, sql, new BeanHandler<SYS_User>(SYS_User.class), loginName,pwd);
			return admin;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * 查询获取一个对象列表
	 * @return
	 */
	public List<SYS_User> getAdminList() {
		Connection conn = getConnection();
		QueryRunner qr = new QueryRunner();
		String sql = "SELECT " + columnFieldMapper4All + " FROM SYS_User";
		try {
			List<SYS_User> list = qr.query(conn, sql, new BeanListHandler<SYS_User>(SYS_User.class));
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return null;
	}

}
